﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using UnityStandardAssets._2D;
using UnityEngine.SceneManagement;

public class GameManager : MonoBehaviour
{
    public static GameManager Instance;


    public GameObject characterPrefab;
    public GameObject playerStart;

    // Transient
    public GameState state { get; private set; }

    public PlatformerCharacter2D character;

    // Events
    public UnityEvent EventOnSceneStart;
    public UnityEvent EventOnGameStart;
    public UnityEvent EventOnDeath;
    public UnityEvent EventOnGameWin;
    public UnityEvent EventOnGameOver;

    public Action<int> EventOnChapterChange;

    public int startAge = 16;
    public float ageYearInSecond = 5f;
    public int age
    {
        get { return startAge + (int)(accumulatedAgeInSecond / ageYearInSecond); }
    }
    private float accumulatedAgeInSecond;
    void Awake()
    {
        Instance = this;
    }


    // Start is called before the first frame update
    void Start()
    {
        state = GameState.Ready;
        
        EventOnSceneStart.Invoke();
        NetworkModule.Instance.SendChapterChangeMessage(1);
        
    }

    // Update is called once per frame
    void Update()
    {
        if (state == GameState.Started)
        {
            accumulatedAgeInSecond += Time.deltaTime;
        }
    }
    /// <summary>
    /// 关卡变话触发
    /// </summary>
    /// <param name="level"></param>
    public void SendChapterChanged(int level)
    {
        if (EventOnChapterChange != null)
        {
            EventOnChapterChange(level);
        }
    }

    public void StartGame()
    {
        accumulatedAgeInSecond = 0f;
        state = GameState.Started;
        Respawn();
        SendChapterChanged(1);
        EventOnGameStart.Invoke();
    }

    public void PlayerDeath()
    {
        EventOnDeath.Invoke();
        GameOver();
    }

    public void GameWin()
    {
        if (state == GameState.Started)
        {
            state = GameState.GameWin;
            character.OnWin();
            EventOnGameWin.Invoke();
        }
        
    }

    public void GameOver()
    {
        if (state == GameState.Started)
        {
            state = GameState.GameOver;
            EventOnGameOver.Invoke();
        }
        
    }

    public void Respawn()
    {
        if (character != null) Destroy(character.gameObject);
        character = Instantiate(characterPrefab, playerStart.transform.position, playerStart.transform.rotation).GetComponent<PlatformerCharacter2D>();
        
    }

    public void ReloadScene()
    {
        SceneManager.LoadScene(0);
    }
}
